﻿var zombies = zombies || {};

zombies.ShoppingCart = function () {
    var self = this;

    //product info
    self.OrderId = ko.observable();
    self.PId = ko.observable();
    self.Name = ko.observable();
    self.Description = ko.observable();
    self.Score = ko.observable();
    self.ProductImg = ko.observable();
    self.Quantity = ko.observable();
    self.QuantityToOrder = ko.observable();
    //self.SumaryScore = ko.observable();

    //current user info
    self.UserName = ko.observable();

    //collections
    self.Products = ko.observableArray();
    self.OrderList = ko.observableArray();

    var OrderListToSave = [];

    var getDataToSave = function () {
        for (var i = 0; i < self.OrderList().length; i++) {
            OrderListToSave.push({
                Username: self.UserName(),
                MemId: 0,
                PId: self.OrderList()[i].PId,
                QuantityToOrder: self.OrderList()[i].QuantityToOrder
            });
        }

        console.log(ko.toJSON(OrderListToSave));

        $.ajax({
            type: "POST",
            url: "/api/MemberProduct/PostProduct",
            data: ko.toJSON(OrderListToSave),
            contentType: "application/json",
            dataType: 'json'
        }).done(function () {
            $.removeCookie(self.UserName(), { path: '/' });
            self.OrderList.removeAll();
            window.location.replace('http://' + window.location.host + '/Member/ListProduct');
        }).fail(function () {
            toastr.error('Add Product Failed !');
        });
    };

    self.totalPrice = ko.computed(function () {
        var total = 0;
        ko.utils.arrayForEach(self.OrderList(), function (shake) {
            var intQuantity = parseInt(shake.QuantityToOrder);
            var intScore = parseInt(shake.Score);

            total += intScore * intQuantity;
        });
        return total;
    }, self);

    self.doDelete = function (item) {
        self.OrderList.remove(item);
        if (self.OrderList().length > 1) {
            $.cookie(self.UserName(), ko.toJSON(self.OrderList()), { expires: 1, path: '/' });
        } else {
            $.removeCookie(self.UserName(), { path: '/' });
        }
    };

    self.doOrder = function (item) {
        getDataToSave();
    };
};

//load data functions
var loadShoppingCart = function (id) {
    ShoppingCartViewModel.OrderList.removeAll();
    $.cookie.json = true;
    var login = 0;
    $.ajax({
        url: '/api/MemberProfile/GetCurrentUser',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items != null) {
            ShoppingCartViewModel.SumaryScore = 0;
            ShoppingCartViewModel.UserName(items);
            var objectNew = $.parseJSON($.cookie(ShoppingCartViewModel.UserName()));
            if (objectNew != null) {
                $.each(objectNew, function (idx, objectNewItem) {
                    ShoppingCartViewModel.OrderList.push(objectNewItem);
                });
            }
            else {
                toastr.error('Bạn chưa đặt hàng !');
            }
        }
    }).error(function () {
        toastr.error('Lỗi bất thường !');
    })

};


//document ready/ Load view model
var ShoppingCartViewModel;
$(document).ready(function () {

    ShoppingCartViewModel = new zombies.ShoppingCart();
    loadShoppingCart();

    ko.applyBindings(ShoppingCartViewModel, document.getElementById("my-container"));
});